<template>
    <rx-dialog @handOk="onOk" @cancel="cancel">
        <rx-layout>
            <div slot="center">
                <a-form :form="form" style="height: 100%;">
                    <a-row>
                        <a-col :span="12">
                            <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" :label="i18n('fieldRemarks','字段备注')">
                                <span>{{ filterParam.fieldLabel }}</span>
                            </a-form-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" :label="i18n('fieldIden','字段标识')">
                                <span>{{ filterParam.fieldName }}</span>
                            </a-form-item>
                        </a-col>
                    </a-row>
                    <a-row>
                        <a-col :span="12">
                            <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" :label="i18n('controlType','控件类型')">
                                <a-select :placeholder="i18n('controlType','控件类型')" @change="controlTypeChange" :getPopupContainer="p=>p.parentNode"
                                          :options="controlTypes" v-decorator="['controlType']"></a-select>
                            </a-form-item>
                        </a-col>
                        <a-col :span="12" v-show="selectControlType!='rangepicker'">
                            <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" :label="i18n('comparisonType','比较类型')">
                                <a-select :placeholder="i18n('comparisonType','比较类型')" :options="opData" :getPopupContainer="p=>p.parentNode" v-decorator="['opType']"></a-select>
                            </a-form-item>
                        </a-col>
                    </a-row>
                    <a-row v-show="selectControlType=='datepicker' || selectControlType=='rangepicker' ">
                        <a-col :span="12">
                            <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" :label="i18n('dateFormat','日期格式')">
                                <a-select :placeholder="i18n('dateFormat','日期格式')" :getPopupContainer="p=>p.parentNode" :options="dateFormats" v-decorator="['format']"></a-select>
                            </a-form-item>
                        </a-col>
                    </a-row>
                    <a-row v-show="selectControlType=='select'">
                        <a-col :span="12">
                            <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" :label="i18n('mulChoice','是否多选')">
                                <a-radio-group
                                    v-decorator="['multiSelect',{rules: [{ required: selectControlType=='select', message: $ti18('rxDecorator.select','请选择') }] }]">
                                    <a-radio :value="false">{{i18n('no','否')}}</a-radio>
                                    <a-radio :value="true">{{i18n('yes','是')}}</a-radio>
                                </a-radio-group>
                            </a-form-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" :label="i18n('valueSource','值来源')">
                                <a-radio-group :options="fromOptions" @change="fromChange"
                                               v-decorator="['from',{rules: [{ required: selectControlType=='select', message: i18n('valueSource','值来源','select') }] }]"/>
                            </a-form-item>
                        </a-col>
                    </a-row>
                    <a-row v-show="selectControlType=='select' && selectFrom=='self'">
                        <a-col :span="24">
                            <a-form-item :label-col="labelCol1" :wrapper-col="wrapperCol1" :label="i18n('option','选项')">
                                <div class="table-operator">
                                    <a-button @click="addRow">{{$ti18('rxList.add','新增')}}</a-button>
                                    <a-button @click="removeRow">{{$ti18('rxList.delBtn','删除')}}</a-button>
                                    <a-button @click="upRow">{{i18n('up','向上')}}</a-button>
                                    <a-button @click="downRow">{{i18n('down','向下')}}</a-button>
                                </div>
                                <rx-grid ref="props"
                                         :bordered="true"
                                         :allowRowSelect="true"
                                         :multiSelect="true"
                                         style="min-height:300px;"
                                         :dataSource="selfParams"
                                         :columns="columns"
                                         :showPage="false">
                                    <span slot="name" slot-scope="{text,record,index,blur}">
                                        <a-input v-model="record.name" @blur="blur(index,'name',text,record)"/>
                                      </span>
                                    <span slot="key" slot-scope="{text,record,index,blur}">
                                        <a-input v-model="record.key" @blur="blur(index,'key',text,record)"/>
                                      </span>
                                </rx-grid>
                            </a-form-item>
                        </a-col>
                    </a-row>
                    <a-row v-show="selectControlType=='select' && selectFrom=='dic'">
                        <a-col :span="24">
                            <a-form-item :label-col="labelCol1" :wrapper-col="wrapperCol1" :label="i18n('dataDicItem','数据字典项')">
                                <rx-input-button
                                    v-decorator="['dicKey',{rules: [{ required:selectControlType=='select' && selectFrom=='dic',message: i18nRequired('dataDicItem','数据字典项必填')}] }]"
                                     @click="selectDic"
                                     style="width: 100%;">
                                </rx-input-button>
                            </a-form-item>
                        </a-col>
                    </a-row>
                    <a-row v-show="selectControlType=='select' && selectFrom=='sql'">
                        <a-col :span="24">
                            <a-form-item :label-col="labelCol1" :wrapper-col="wrapperCol1" :label="i18n('customSQL','自定义SQL')">
                                <rx-input-button ref="sql" @click="openCustomQuery"
                                                 v-decorator="['sql',{rules: [{ required:selectControlType=='select' &&  selectFrom=='sql',message: i18nRequired('customSQL','自定义SQL必填')}] }]"/>
                            </a-form-item>
                        </a-col>
                    </a-row>
                    <a-row v-show="selectControlType=='select' && selectFrom=='sql'">
                        <a-col :span="12">
                            <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" :label="i18n('textField','文本字段')">
                                <a-select :options="sqlFields"
                                          :getPopupContainer="p=>p.parentNode"
                                          v-decorator="['sql_textfield',{rules: [{ required:selectControlType=='select' &&  selectFrom=='sql',message: i18nRequired('textField','文本字段必填')}] }]"/>
                            </a-form-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" :label="i18n('numberField','数值字段')">
                                <a-select :options="sqlFields"
                                          :getPopupContainer="p=>p.parentNode"
                                          v-decorator="['sql_valuefield',{rules: [{ required:selectControlType=='select' &&  selectFrom=='sql',message: i18nRequired('numberField','数值字段必填')}] }]"/>
                            </a-form-item>
                        </a-col>
                    </a-row>
                </a-form>
            </div>
        </rx-layout>
    </rx-dialog>
</template>

<script>
import {RxGrid, Util, Dialog, RxInputButton, RxLayout, BaseForm} from "@lowcode/jpaas-common-lib";
import SysTreeApi from "@/api/system/core/sysTree";

export default {
    name: "chart-condition",
    mixins: [BaseForm],
    props: {
        layerid: {
            type: String,
            default: ""
        },
        destroy: {
            type: Function
        },
        filterParam: {
            type: Object
        }
    },
    components: {
        RxGrid,
        RxInputButton,
        RxLayout
    },
    data() {
        return {
            labelCol: {span: 6},
            wrapperCol: {span: 18},
            labelCol1: {span: 3},
            wrapperCol1: {span: 19},
            mdl: {},
            selectFrom: '',
            selectControlType: '',
            /**
             * {label: '文本框', value: 'textbox'},
             {label: '日期', value: 'datepicker'},
             {label: '日期范围', value: 'rangepicker'},
             {label: '下拉框', value: 'select'}
             */
            controlTypes:[{label: this.i18n('controlTypes.textBox','文本框'), value: 'textbox'},
                {label: this.i18n('controlTypes.select','下拉框'), value: 'select'},
                {label: this.i18n('controlTypes.date','日期'), value: 'datepicker'},
                {label: this.i18n('controlTypes.dateRange','日期范围'), value: 'rangepicker'}
                ],
            opData:[],
            opData1: [{'value': 'EQ', 'label': this.i18n('options.eq','等于')},
                {'value': 'NEQ', 'label': this.i18n('options.neq','不等于')},
                {'value': 'IN', 'label': this.i18n('options.include','包含')},
                {'value': 'LK', 'label': this.i18n('options.lk','模糊匹配')},
                {'value': 'LEK', 'label': this.i18n('options.leftMatch','左模糊匹配')},
                {'value': 'RIK', 'label': this.i18n('options.rightMatch','右模糊匹配')}],
            opData2:[{value:'EQ',label:this.i18n('options.eq','等于')},
                {value:'LESS',label:this.i18n('options.lt','小于')},
                {value:'LESSEQUAL',label:this.i18n('options.le','小于等于')},
                {value:'GREAT',label:this.i18n('options.gt','大于')},
                {value:'GREAT_EQUAL',label:this.i18n('options.ge','大于等于')}],
            fromOptions: [{'value': 'self', 'label': this.i18n('custom','自定义')},
                {'value': 'dic', 'label': this.i18n('dataDictionary','数据字典')},
                {'value': 'sql', 'label': this.i18n('customSQL','自定义SQL')}],
            dateFormats:[{label:'YYYY-MM-DD',value:'YYYY-MM-DD'},
                {label:'YYYY-MM-DD HH:mm:ss',value:'YYYY-MM-DD HH:mm:ss'}],
            selfParams: [],
            columns: [
                {
                    title: this.$ti18('rxList.index','序号'),
                    type: 'indexColumn',
                    width: 80,
                    dataIndex: 'serial',
                    scopedSlots: {customRender: 'serial'}
                },
                {title: this.$ti18('rxForm.name','名称'), dataIndex: 'name', width: 120, allowCellEdit: true, scopedSlots: {customRender: 'name'}},
                {title: this.i18n('idenName','标识名'), dataIndex: 'key', width: 120, allowCellEdit: true, scopedSlots: {customRender: 'key'}}
            ],
            dicTree: [],
            sqlFields: [],
        }
    },
    created() {
        //条件
        if (this.filterParam.condition) {
            if(this.selectFrom=="dic"){
                this.loadDicTree();
            }
            this.setData(this.filterParam.condition);
        }
    },
    methods: {
        i18n(name,text,key){
            return this.$ti18(name,text,"ChartCondition",key);
        },
        i18nRequired(name,text,key){
            let nameVal = this.$ti18(name,text,"ChartCondition",key);
            let tipVal = this.i18n("required", "必填");
            return nameVal + tipVal;
        },
        onOk(e) {
            var self = this;
            if (this.validate(function () {
                Util.closeWindow(self, "ok", self.getData());
            })) ;
            e.loading = false;
        },
        cancel() {
            Util.closeWindow(this, "cancel");
        },
        loadDicTree() {
            let appId=this.$route.query.appId;
            SysTreeApi.listDicTree(appId).then(res => {
                var cloneData = [];
                res.forEach(function (item) {
                    cloneData.push({
                        title: item.name,
                        key: item.treeId,
                        value: item.alias,
                        parentId: item.parentId
                    })
                })
                var treeData = Util.listToTree(cloneData, "key", "parentId");
                this.dicTree = treeData;
            })
        },
        validate(callback) {
            var self = this;
            this.form.validateFields((err, values) => {
                if (err) {
                    return;
                }
                self.mdl = values;
                callback();
            });
        },
        getData() {
            this.mdl.props = JSON.stringify(this.$refs.props.getData());
            var sql = this.$refs.sql.getVal();
            this.mdl.sql = sql.value;
            this.mdl.sql_name = sql.text;
            this.mdl.sqlFields = this.sqlFields;
            return this.mdl;
        },
        changeData(e, field) {
            this.mdl[field] = e.target.checked;
        },
        fromChange(e) {
            this.selectFrom = e.target.value;
            if(this.selectFrom=="dic"){
                this.loadDicTree();
            }
        },
        addRow() {
            this.$refs.props.addRow();
        },
        removeRow() {
            this.$refs.props.removeRows();
        },
        upRow() {
            this.$refs.props.moveUp();
        },
        downRow() {
            this.$refs.props.moveDown();
        },
        openFormEntityDataType(vm) {
            var self = this;
            var config = {curVm: this, widthHeight: ['800px', '600px'], data: {multiSelect: false}};
            Dialog.openFormEntityDataTypeDialog(config, function (ary) {
                var data = ary[0];
                vm.setVal(data.id, data.name);
            })
        },
        openCustomQuery(vm) {
            Dialog.openCustomDataDialog({
                curVm: this, widthHeight: ['1200px', '600px']
            }, function (self, data) {
                self.loadFields(data);
                vm.setVal(data.key, data.name);
            })
        },
        //选择数据字典
        selectDic(vm){
            let conf = {
                curVm: this, data: {allowTree:true}, widthHeight: ['800px', '600px'],
            }
            let self_ = this;
            Dialog.openSysDicDialog(conf,function (curVue, row) {
                vm.setVal(row.alias,self_.$i18(row.name,"名称"));
            })
        },
        loadFields(row) {
            var fieldStr = row.resultField;
            var whereStr = row.whereField;
            if (fieldStr) {
                var fileds = JSON.parse(fieldStr);
                var ary = fileds.map(function (item) {
                    return {
                        value: item.fieldName,
                        label: item.comment
                    }
                })
                this.sqlFields = ary;
            }
        },
        setData(data) {
            debugger
            this.mdl=Object.assign({multiSelect:false,from:'self'},data);
            this.selectFrom=this.mdl.from;
            this.selectControlType=this.mdl.controlType;
            //日期控件
            if(this.selectControlType=="datepicker"){
                this.opData=this.opData2;
            }else {
                this.opData=this.opData1;
            }
            if(this.mdl.sql) {
                this.mdl.sql = '{value:\'' + this.mdl.sql + '\',text:\'' + this.mdl.sql_name + '\'}';
            }
            if(this.mdl.grant){
                this.mdl.grant = '{value:\'' + this.mdl.grant + '\',text:\'' + this.mdl.grant_name + '\'}';
            }
            this.sqlFields = this.mdl.sqlFields || [];
            var props=this.mdl.props || '[]';
            this.selfParams=JSON.parse(props);
            this.form.setFieldsValue(this.mdl)
        },
        controlTypeChange(value){
            this.selectControlType = value;
            //日期
            if(this.selectControlType=="datepicker"){
                this.opData=this.opData2;
            }else {
                this.opData=this.opData1;
            }
            this.mdl.opType="EQ";
        }
    }
}
</script>
<style scoped>

</style>